package com.scientificInfo.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.scientificInfo.bean.*;
import com.scientificInfo.entity.TSMResult;
import com.scientificInfo.server.*;
import com.scientificInfo.util.DateUtil;
import com.scientificInfo.util.UuidUtil;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.Cleaner;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Controller
public class AdminController {

    @Autowired
    AdminServer adminServer;

    //执行数据库发送消息SQL语句
    private void sendMessage(Message message) {
        adminServer.insertMessage(message);
    }

    //获得实时日期数据
    private String getDataInfo() {
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
        int day = Calendar.getInstance().get(Calendar.DATE);
        String monthDate = String.valueOf(month);
        String dayDate = String.valueOf(day);

        if (month < 10) {
            monthDate = "0" + String.valueOf(month);
        }
        if (day < 10) {
            dayDate = "0" + String.valueOf(day);
        }
        String date = year + monthDate + dayDate;

        return date;
    }

    //构成消息
    private Message makeUpMessage(String teaId, String product, int ope) {
        Message message = new Message();
        String msg = "你的" + product + "被管理员，执行了：";
        if (ope == 1) {
            msg += "通过";
        } else if (ope == 2) {
            msg += "下架";
        }
        msg += " 操作。请进入有关页面进行查看。";

        message.setBegin(DateUtil.YMDToNum());
        message.setEnd(DateUtil.GetEndDate());
        message.setFromuser("admin");
        message.setTouser(teaId);
        message.setId(UuidUtil.getUuid(10));
        message.setMessage(msg);
        return message;
    }


    //给全体教师发消息
    @RequestMapping(value = "/sendMessageToAll")
    @ResponseBody
    private TSMResult sendMessage(@RequestParam("end") String end, @RequestParam("message") String message) throws UnsupportedEncodingException {
        message = new String(message.getBytes("iso-8859-1"), "utf-8");
        String id = UuidUtil.getUuid(10);
        TSMResult tsmResult = new TSMResult();
        tsmResult.setMessage("请求成功");

        Message message1 = new Message();
        String fromuser = "admin";
        message1.setFromuser(fromuser);
        message1.setBegin(Integer.parseInt(getDataInfo()));
        message1.setEnd(Integer.parseInt(end));
        message1.setMessage(message);
        message1.setId(id);
        message1.setTouser("allTeacher");

        int data = adminServer.insertMessage(message1);
        tsmResult.setMessage((data == 0) ? "发送失败！" : "发送成功！");
        tsmResult.setData(data);
        return tsmResult;
    }

    //给某位教师发私信
    @RequestMapping(value = "/sendMessageToTeacher")
    @ResponseBody
    private TSMResult sendMessageToTeacher(@RequestParam("teacherId") String teacherid,
                                           @RequestParam("message") String message,
                                           @RequestParam("end") String end) throws UnsupportedEncodingException {

        message = new String(message.getBytes("iso-8859-1"), "utf-8");
        String id = UuidUtil.getUuid(10);
        TSMResult tsmResult = new TSMResult();
        String fromuser = "admin";
        Message message1 = new Message();
        message1.setFromuser(fromuser);
        tsmResult.setCode(200);
        message1.setBegin(Integer.parseInt(getDataInfo()));
        message1.setEnd(Integer.parseInt(end));
        message1.setMessage(message);
        message1.setId(id);
        message1.setTouser(teacherid);
        int data = adminServer.insertMessage(message1);
        tsmResult.setMessage((data == 0) ? "发送失败！" : "发送成功！");
        tsmResult.setData(data);
        return tsmResult;
    }

    //暂时没用
    @RequestMapping("/selAllNewPaper")
    @ResponseBody
    public TSMResult selAllNewPaper(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        PageHelper.startPage(pn, 5);
        List<Paper> papers = adminServer.getAllPaperNotCheck();
        PageInfo page = new PageInfo(papers, 5);
        TSMResult tsmResult = new TSMResult();
        tsmResult.setData(page);
        tsmResult.setCode(200);
        tsmResult.setMessage("请求完成");
        return tsmResult;
    }

    //所有著作
    @PostMapping("/seeAllWorks")
    @ResponseBody
    public TSMResult seeAllNewWorks(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        PageHelper.startPage(pn, 5);
        List<Works> works = adminServer.seeAllWorks();
        PageInfo page = new PageInfo(works, 5);
        return new TSMResult(200, "请求完成", page);
    }

    //改变著作的操作码
    //注意 需要先更新数据库值 同时更新前端的页面显示的LIST
    @GetMapping("/reUpdateWorks")
    @ResponseBody
    public TSMResult reUpdateWorks(String worksId, int operaCode) {

        TSMResult tsmResult = new TSMResult();
        adminServer.updateWorksStatu(worksId, operaCode);
        tsmResult.setMessage("操作成功");
        PageHelper.startPage(1, 5);

        List<Works> list = adminServer.seeAllWorks();
        PageInfo page = new PageInfo(list, 5);
        tsmResult.setData(page);
        return tsmResult;
    }

    //暂时没用
    @RequestMapping("/checkPaperVail")
    @ResponseBody
    public TSMResult checkPaperReal(String papersId) {
        TSMResult tsmResult = new TSMResult();
        tsmResult.setMessage("请求成功");
        tsmResult.setCode(200);
        tsmResult.setData(new Boolean(true));
        return tsmResult;
    }

    //暂时没用
    @RequestMapping("/updatePaper")
    @ResponseBody
    public TSMResult updatePaper(String paperId, int operaCode) {
        System.out.println(paperId + "  " + operaCode);
        TSMResult tsmResult = new TSMResult();
        adminServer.updatePaperStatu(paperId, operaCode);
        String[] info = adminServer.selectPaperNameById(paperId);
        String str = "论文《" + info[1] + "》";
        sendMessage(makeUpMessage(info[0], str, operaCode));
        PageHelper.startPage(1, 5);
        List<Paper> papers = adminServer.getAllPaperNotCheck();
        PageInfo page = new PageInfo(papers, 5);
        tsmResult.setCode(200);
        tsmResult.setMessage("操作成功");
        tsmResult.setData(page);
        return tsmResult;
    }

    //更改论文的状态码
    @RequestMapping("/reUpdatePaper")
    @ResponseBody
    public TSMResult reUpdatePaper(String paperId, int operaCode) {
        TSMResult tsmResult = new TSMResult();
        String message = "操作成功！";
        Integer data;
        tsmResult.setCode(200);
        try {
            adminServer.updatePaperStatu(paperId, operaCode);
        } catch (Exception e) {
            message = "操作失败";
            data = 0;
            tsmResult.setMessage(message);
            tsmResult.setData(data);
            return tsmResult;
        }
        String[] info = adminServer.selectPaperNameById(paperId);
        String str = "论文《" + info[1] + "》";
        sendMessage(makeUpMessage(info[0], str, operaCode));
        tsmResult.setMessage(message);
        tsmResult.setData(1);
        return tsmResult;
    }

    //暂时没用
    @RequestMapping("/selAllNewPatent")
    @ResponseBody
    public TSMResult selAllNewPatent(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        TSMResult tsmResult = new TSMResult();
        PageHelper.startPage(pn, 5);
        List<Patent> patents = adminServer.getAllPatentNotCheck();
        PageInfo page = new PageInfo(patents, 5);
        tsmResult.setData(page);
        tsmResult.setMessage("操作成功");
        tsmResult.setCode(200);
        return tsmResult;
    }

    //更改专利的状态码
    @RequestMapping("/updatePatent")
    @ResponseBody
    public TSMResult updatePatent(String patentId, int operaCode) {
        TSMResult tsmResult = new TSMResult();
        try {
            adminServer.updatePatentStatu(patentId, operaCode);
        } catch (Exception e) {
            tsmResult.setData(0);
            tsmResult.setCode(200);
            tsmResult.setMessage("操作成功");
            return tsmResult;
        }
        String[] info = adminServer.selectPatentNameById(patentId);
        String str = "专利《" + info[1] + "》";
        sendMessage(makeUpMessage(info[0], str, operaCode));
        tsmResult.setData(1);
        tsmResult.setCode(200);
        tsmResult.setMessage("操作成功");
        //System.out.println(JSONObject.toJSONString(tsmResult));
        return tsmResult;
    }

    //暂时没用
    @RequestMapping("/selAllNewProject")
    @ResponseBody
    public TSMResult selAllNewProject(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        PageHelper.startPage(pn, 5);
        List<Project> projects = adminServer.getAllProjectNotCheck();
        PageInfo page = new PageInfo(projects, 5);
        return new TSMResult(200, "操作成功", page);
    }

    //更改项目状态码
    @RequestMapping("/updateProject")
    @ResponseBody
    public TSMResult updateProject(String projectId, int operaCode) {
        TSMResult tsmResult = new TSMResult();
        try {
            adminServer.updateProjectStatu(projectId, operaCode);
        } catch (Exception e) {
            tsmResult.setMessage("操作成功");
            tsmResult.setCode(200);
            tsmResult.setData(0);
        }
        String[] info = adminServer.selectProjectNameById(projectId);
        String str = "项目《" + info[1] + "》";
        sendMessage(makeUpMessage(info[0], str, operaCode));
        tsmResult.setMessage("操作成功！");
        tsmResult.setCode(200);
        tsmResult.setData(1);
        return tsmResult;
    }

    //查询所有状态的论文
    @RequestMapping("/selCheckAndRemovePaper")
    @ResponseBody
    public TSMResult selCheckAndRemovePaper(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {

        PageHelper.startPage(pn, 5);
        List<Paper> papers = adminServer.selectCheckAndRemovePaper();
        //查询
        for (Paper paper : papers) {
            Source source = adminServer.isExistsPaperFile(paper.getPapername() + ".doc");
            if (source != null) {
                //存储了文件信息 才能给予下载
                paper.setIsDownloadAllowed(1);
            }
        }
        PageInfo page = new PageInfo(papers, 5);
        return new TSMResult(200, "操作成功", page);
    }

    //查询所有状态的专利
    @RequestMapping("/selCheckAndRemovePatent")
    @ResponseBody
    public TSMResult selCheckAndRemovePatent(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {

        PageHelper.startPage(pn, 5);
        List<Patent> patents = adminServer.selectCheckAndRemovePatent();
        PageInfo page = new PageInfo(patents, 5);
        return new TSMResult(200, "操作成功", page);
    }

    //查询所有状态的项目
    @RequestMapping("/selCheckAndRemoveProject")
    @ResponseBody
    public TSMResult selCheckAndRemoveProject(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {

        PageHelper.startPage(pn, 5);
        List<Project> projects = adminServer.selectCheckAndRemoveProject();
        PageInfo page = new PageInfo(projects, 5);
        return new TSMResult(200, "操作成功", page);
    }

    //查询所有教师
    @RequestMapping("/selAllTeacher")
    @ResponseBody
    public TSMResult selAllTeacher(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        TSMResult tsmResult = new TSMResult();
        PageHelper.startPage(pn, 5);
        List<Teacher> teachers = adminServer.selectAllTeacher();
        PageInfo page = new PageInfo(teachers, 5);
        tsmResult.setData(page);
        tsmResult.setCode(200);
        tsmResult.setMessage("操作成功");
        return tsmResult;
    }

    //添加教师
    @RequestMapping("/addTeacher")
    @ResponseBody
    public TSMResult addTeacher(Teacher teacher) {
        TSMResult tsmResult = new TSMResult();
        teacher.setTeacherid(UuidUtil.getUuid(6));
        teacher.setTeacherstatu(1);
        adminServer.insertTeacher(teacher);
        PageHelper.startPage(1, 5);
        List<Teacher> teachers = adminServer.selectAllTeacher();
        PageInfo page = new PageInfo(teachers, 5);
        tsmResult.setMessage("操作成功");
        tsmResult.setCode(200);
        tsmResult.setData(page);
        return tsmResult;
    }

    //删除教师
    @RequestMapping("/deleteTeacher")
    @ResponseBody
    public TSMResult deleteTeacher(Teacher teacher) {
        TSMResult tsmResult = new TSMResult();
        adminServer.deleteTeacher(teacher.getTeacherid());
        PageHelper.startPage(1, 5);
        List<Teacher> teachers = adminServer.selectAllTeacher();
        PageInfo page = new PageInfo(teachers, 5);
        tsmResult.setMessage("操作成功");
        tsmResult.setCode(200);
        tsmResult.setData(page);
        return tsmResult;
    }

    //更改教师
    @RequestMapping("/updateTeacher")
    @ResponseBody
    public TSMResult updateTeacher(String teacherId, int operaCode) {
        //修改老师状态。
        TSMResult tsmResult = new TSMResult();
        Boolean result = adminServer.updateTeacher(teacherId, operaCode) == 1;
        tsmResult.setData(new Boolean(result));
        tsmResult.setCode(200);
        tsmResult.setMessage("更改成功！");
        return tsmResult;
    }

    //查询所有教师（暂时没用）
    @RequestMapping("/getTeacherList")
    @ResponseBody
    public TSMResult getTeacherList() {
        TSMResult tsmResult = new TSMResult();
        tsmResult.setCode(200);
        tsmResult.setMessage("请求成功");
        List<Teacher> teacherList = new LinkedList<>();
        teacherList = adminServer.selectAllTeacher();
        tsmResult.setData(teacherList);
        return tsmResult;
    }

    //发送消息的时候 查询所有没有被注销的教师
    @RequestMapping("/getTeacherListNotLogOut")
    @ResponseBody
    public TSMResult getTeacherListNotLogOut() {

        int status = 1;  //只能给没被注销的教师 发消息
        TSMResult tsmResult = new TSMResult();
        tsmResult.setCode(200);
        tsmResult.setMessage("请求成功");
        List<Teacher> teacherList = new LinkedList<>();
        teacherList = adminServer.selectTeacherNotLogOut(status);
        tsmResult.setData(teacherList);
        return tsmResult;
    }

    //管理员更改信息
    @RequestMapping("/adminUpdateInfo")
    @ResponseBody
    public TSMResult adminUpdateInfor(@RequestBody(required = false) Admin admin, HttpSession session) {

        System.out.println("管理员信息：" + admin);
        TSMResult tsmResult = new TSMResult();
        int data = adminServer.updateAdmin(admin);
        tsmResult.setData(data);
        tsmResult.setMessage("更改成功");
        return tsmResult;
    }

    //查询管理员信息
    @RequestMapping("/getAdminInfo")
    @ResponseBody
    public TSMResult getAdminInfor(@RequestParam("adminId") String adminId) {
        Admin admin = adminServer.selectAdminInforById(adminId);
        return new TSMResult(200, "查询成功!", admin);
    }

    //管理员对论文审核评分
    @RequestMapping(value = "/score", method = RequestMethod.POST)
    @ResponseBody
    public TSMResult score(String name, int score) {
        TSMResult tsmResult = new TSMResult();
        int flag = adminServer.scorePaper(name, score);
        if (flag > 0) {
            tsmResult.setMessage("评分成功");
            tsmResult.setData(flag);
        } else {
            tsmResult.setMessage("评分失败");
        }
        return tsmResult;
    }

    //管理员对科研项目进行评分
    @RequestMapping(value = "/scoreProject", method = RequestMethod.POST)
    @ResponseBody
    public TSMResult scoreProject(String projectId, int score) {
        int code = adminServer.scoreProject(projectId, score);
        String message = "评分成功";
        if (code == 0) {
            message = "评分失败";
        }
        return new TSMResult(200, message, code);
    }

    //管理员对科研专利进行评分
    @RequestMapping(value = "/scorePatent", method = RequestMethod.POST)
    @ResponseBody
    public TSMResult scorePatent(String patentId, int score) {
        int code = adminServer.scorePatent(patentId, score);
        String message = "评分成功";
        if (code == 0) {
            message = "评分失败";
        }
        return new TSMResult(200, message, code);
    }


    //查询是否存在论文 存在论文文件信息的 才给予下载
    @RequestMapping(value = "/isExistsFilename", method = RequestMethod.GET)
    @ResponseBody
    public TSMResult isExistsFilename(
            @RequestParam("paperName") String paperName) {
        //处理中文
        Boolean isExists = false;
        try {
            paperName = new String(paperName.getBytes("ISO-8859-1"), "UTF-8");
            paperName = paperName + ".doc";
            Source source = adminServer.isExistsPaperFile(paperName);
            isExists = (source == null) ? false : true;
        } catch (Exception e) {
            System.out.println("检测到异常！");
            e.printStackTrace();
        }
        return new TSMResult(200, "查询成功", isExists);
    }

    //查询科研人员登录系统的次数信息
    @RequestMapping(value = "/showLoginCountData", method = RequestMethod.GET)
    @ResponseBody
    public TSMResult showLoginCountData() {
        List<LoginCount> list = adminServer.showLoginCountData();
        return new TSMResult(200, "查询成功", list);
    }
}
